package org.tokaf.datasearcher;

import java.sql.SQLException;

import com.hp.hpl.jena.db.DBConnection;
import com.hp.hpl.jena.db.IDBConnection;
import com.hp.hpl.jena.db.ModelRDB;

/**
 * <p>Jena DataSearcher, which works with MySQL database.</p> <p>Copyright
 * (c) 2006</p>
 * @author Alan Eckhardt
 * @version 1.0
 */
public class JenaMySQLSearcher extends JenaSearcher {
	IDBConnection conn;

	public JenaMySQLSearcher() {
		userName = "test";
		password = "";
	}

	public Object clone() {
		JenaMySQLSearcher newInstance = new JenaMySQLSearcher();
		newInstance.initSource(this);
		newInstance.initSearchTime = this.initSearchTime;
		newInstance.initSourceTime = this.initSourceTime;
		newInstance.norm = this.norm;
		newInstance.name = this.name;

		newInstance.alreadySeen = this.alreadySeen;
		newInstance.results = this.results;
		newInstance.qexec = this.qexec;
		newInstance.soln = this.soln;
		newInstance.searchIndex = this.searchIndex;
		return newInstance;
	}

	public void finalize() throws Throwable {
		super.finalize();
		try {
			if (conn != null)
				conn.close();
			model.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * initSource
	 * @param db String
	 * @return int
	 */
	public int initSource(String db) {
		long startTime = System.nanoTime();
		// Load the Driver
		String className = "com.mysql.jdbc.Driver"; // path of driver class
		try {
			Class.forName(className); // load driver
		} catch (ClassNotFoundException ex) {
		}

		String DB_URL = "jdbc:mysql://localhost/" + db; // URL of database
														// server
		String DB_USER = userName; // database user id
		String DB_PASSWD = password; // database password
		String DB = "MySQL"; // database type

		// Create database connection
		conn = new DBConnection(DB_URL, DB_USER, DB_PASSWD, DB);
		// Create a model in the database
		// model = ModelRDB.open(conn);
		model = null;
		try {
			model = ModelRDB.open(conn);
		} catch (Exception ex) {
			model = ModelRDB.createModel(conn);
		}
		initSourceTime += System.nanoTime() - startTime;
		return 1;
	}

}
